import { postMemberInfo } from "./../../api/member";
import { defineStore } from "pinia";
import { ref } from "vue";
import type { UserInfo } from "../../types/member";
import { useGlobalStore } from "./global";
import AppLanguages from "../../data/languageList";
import { postChangeLanguage } from "../../api/api";
import { useCookie } from "nuxt/app";
import { persist } from "pinia-plugin-persistedstate";

export const useMemberStore = defineStore(
  "memberStore",
  () => {
    // 当前应用语言
    const AppLang = ref<string | undefined>(undefined);
    // 当前应用语言的索引
    const AppLangIndex = ref<number>(0);
    // 应用支持的所有语言列表
    const AppLangList = ref(AppLanguages);

    // 更新应用语言
    async function postAppLang(lang: string) {
      if (lang == AppLang.value) return;
      let res = await postChangeLanguage(lang);
      if (res.code === 200) {
        location.reload();
      }
    }

    // 设置应用语言
    function setAppLang(lang: string) {
      let cookie_lang = useCookie("lang").value || "en";
      let index = AppLangList.value.findIndex(
        (item) => item.value === cookie_lang
      );
      if (index == -1) {
        index = 0;
      }
      AppLang.value = lang;
      AppLangIndex.value = index;
    }

    // 用户信息
    const profile = ref<UserInfo | undefined>(undefined);
    // 登录状态
    const isLogined = ref<boolean>(false);

    // 使用 useCookie 替代默认的持久化
    const cookieProfile = useCookie<any>("profile");

    // 修改 getProfileLocal 和 setProfileLocal 使用 cookie
    function getProfileLocal() {
      if (process.server) return;
      profile.value = JSON.parse(localStorage.getItem("profile") as string);
    }

    function setProfileLocal() {
      if (process.server) return;
      cookieProfile.value = JSON.stringify(profile.value);
      localStorage.setItem("profile", JSON.stringify(profile.value));
    }

    // 修改 clearProfile 使用 cookie
    const clearProfile = () => {
      if (process.server) return;
      profile.value = undefined;
      isLogined.value = false;
      cookieProfile.value = undefined;
      localStorage.removeItem("profile");
    };

    // 更新用户信息
    const updateProfile = (val: any) => {
      if (profile.value) {
        Object.assign(profile.value, val);
      } else {
        profile.value = val;
      }

      isLogined.value = true;
      updateBase64Image()
      handlePersonalTags();
      setProfileLocal();
    };

    const updateBase64Image = () => {
      if (profile.value?.headimgurl_base) {
        if (
          profile.value?.headimgurl_base.startsWith("data:image/png;base64,")
        ) {
          profile.value.headimgurl_base = profile.value?.headimgurl_base;
        } else {
          profile.value.headimgurl_base =
            "data:image/png;base64," + profile.value?.headimgurl_base;
        }
      }
    }

    // 处理用户个人标签
    function handlePersonalTags() {
      if (!profile.value) return;
      const globalStore = useGlobalStore();
      // 处理证书、语言、机型、教育背景等标签
      let certIds = profile.value?.certificate_id.split(",") || [];
      let languageIds = profile.value?.language_id.split(",") || [];
      let air_modelIds = profile.value?.airmodel_id.split(",") || [];
      let educationId = profile.value?.education_id;

      // 过滤空值
      certIds = certIds.filter((item) => item != "");
      languageIds = languageIds.filter((item) => item != "");
      air_modelIds = air_modelIds.filter((item) => item != "");

      profile.value.certificate = certIds.map((id) => {
        return globalStore.certificateList?.find((item) => item.id == id)
          ?.title;
      });
      profile.value.language = languageIds.map((id) => {
        return globalStore.languageList?.find((item) => item.id == id)?.title;
      });
      profile.value.air_model = air_modelIds.map((id) => {
        return globalStore.airModelList?.find((item) => item.id == id)?.title;
      });
      profile.value.education = globalStore?.educationList?.find(
        (item) => item.id == educationId
      )?.title;
    }

    // 从服务器获取用户信息
    const getProfileData = async () => {
      let res = await postMemberInfo();
      if (res.code === 200 && res.data !== null && res.data !== undefined) {
        updateProfile(res.data);
      } else {
        // 如果服务器返回无效数据，清除本地状态
        clearProfile();
      }
    };

    // 在页面加载时检查登录状态
    if (!isLogined.value && cookieProfile.value) {
      // 如果未登录但 cookie 中有用户信息，更新状态
      updateProfile(cookieProfile.value);
    }

    // 获取是否操作提示
    const getTipVisible = () => {
      let flag = true;
      let time = localStorage.getItem("tip_time");
      let tip_end_time: number = 0;
      if (time) {
        tip_end_time = parseInt(time);
      }
      if (tip_end_time && tip_end_time > 0) {
        let currentTime = new Date().getTime();
        let time_48 = 1000 * 60 * 60 * 24 * 2; // 2天未点击显示提示
        if (currentTime - tip_end_time > time_48) {
          flag = true;
        } else {
          flag = false;
        }
      }
      return flag;
    };
    const setTipVisibleEndTime = () => {
      // 设置当前时间戳为离开我的考试页面时间
      setTipTime();
    };
    function setTipTime() {
      let tip_end_time = new Date().getTime();
      localStorage.setItem("tip_time", JSON.stringify(tip_end_time));
    }
    return {
      AppLangList,
      profile,
      isLogined,
      AppLang,
      AppLangIndex,
      getProfileLocal,
      updateProfile,
      setAppLang,
      clearProfile,
      getProfileData,
      postAppLang,
      handlePersonalTags,
      getTipVisible,
      setTipVisibleEndTime,
    };
  },
  {
    persist: {
      omit: ["AppLang"],
    },
  }
);
